﻿package javase.socket.server;


import java.net.*;
import java.io.*;
import java.util.*;

public class ChatServer3 {
	public static void main(String args[])
	{
	    ServerSocket ss=null;
	//    Vector users=new Vector();		//存储线程对象(包含Socket信息)
	    HashMap users=new HashMap();
	    int a_count=0;
	    int i=0;
	    boolean Running=true;
		DataInputStream s_in;
		String[] name=null;
	    System.out.println("服务器已启动!");
	    try
	    {
	    	ss=new ServerSocket(8888);	//服务器监听本地1235端口
	    }
	    catch(Exception e)
	    {
	    	System.out.println("new ServerSocket()failed!");
	    	return;
	    }
	    try
	    {
	    	while(Running)
	    	{
		        Socket s=ss.accept();		//等待客户端连接
		        System.out.println("已与"+s.getInetAddress().getHostAddress()+"建立连接!"+"对方端口:"+s.getPort());	
		        ServerThread st=new ServerThread(s,users);
				s_in=new DataInputStream(s.getInputStream());
				name[i]=s_in.readUTF();i++;
		        users.put(name[i].substring(6),st);  	//存放线程对象st和名称
		        new Thread(st).start();					//启动会话线程   
		        Set nameset=users.keySet();
		        Iterator it=nameset.iterator();
		        while(it.hasNext())
		        {
		        	String temp=(String)it.next();
		        	ServerThread sr=(ServerThread)users.get(temp);
		        	sr.write("欢迎用户#"+temp+"#来到JQB专用聊天室");
		        }
		        System.out.println("等待连接!");
	    	}
	    }
	    catch(Exception e)
	    {
	    	System.out.print("服务器挂了!");
	    }
	}
}
class ServerThread implements Runnable{
	
	HashMap users;
    Socket s_s=null;
    DataInputStream s_in=null;
    DataOutputStream s_out=null;
    int count=0;
    public ServerThread(Socket s,HashMap threads)
    {
    	s_s=s;
    	users=threads;
    	try
    	{
    		s_in=new DataInputStream(s_s.getInputStream());
    		s_out=new DataOutputStream(s_s.getOutputStream());
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    }
    public void run()
    {
    	System.out.println("线程启动，对话中。。。");
    	try
    	{
    		while(true)
    		{      	   
    			String str=s_in.readUTF();	//等待客户端发送消息,读入str
    			if(str==null)
    				continue;
    			if(str.substring(0,3).equals("#q#"))//私聊#p#name#conversation,群聊#all#conversation
    			{
    				String name=str.substring(3,str.indexOf("#",3));//保存私聊对象姓名
    				String msg=str.substring(str.indexOf("#",3)+1);//会话内容
    				ServerThread sr=(ServerThread)users.get(name);
    				sr.write(name+"悄悄地说:"+msg);
    			}
    			else if(str.subSequence(0,5).equals("#all#"))
    			{
    				String msg=str.substring(5);//会话内容
    				Set nameset=users.keySet();
    				Iterator it=nameset.iterator();
    				while(it.hasNext())
    				{
    					String temp=(String)it.next();
    					ServerThread sr=(ServerThread)users.get(temp);
    					sr.write(temp+"说:"+msg);
    				}
    			}
    			else if(str.substring(0,6).equals("#List#"))//#List#username为添加用户
    			{
    				Set nameset=users.keySet();
    				Iterator it=nameset.iterator();
    				while(it.hasNext())
    				{
    					String temp=(String)it.next();
    					ServerThread sr=(ServerThread)users.get(temp);
    					sr.write(str);
    				}
    			}
    			else
    			{
    				continue;
    			}
    		}
    	}
    	catch(Exception e)
    	{
    		if(!s_s.isClosed())
	    		   e.printStackTrace();
    	}
    }
    public void write(String msg)
    {
    	synchronized(s_out)
    	{
    		try
    		{
    			s_out.writeUTF(msg);
    		}
    		catch(IOException e)
    		{}
        }
    }
}

